#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QLabel>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle(tr("Qt Zawody Wędkarskie %1").arg(QApplication::applicationVersion()));

    //------StatusBar-------------------------
    m_statusLabel = new QLabel(this);
    m_progressBar = new QProgressBar(this);

    if (podlaczDoBazy())
    {
        m_statusLabel->setText("Status połącznienia z bazą: <font color=\"green\">OK</font>");
    }else{
        m_statusLabel->setText("Status połącznienia z bazą: <font color=\"red\">NOT OK</font>");
    }

    ui->statusBar->addWidget(m_statusLabel,ui->statusBar->width());
    ui->statusBar->addWidget(m_progressBar);
    m_progressBar->setMaximumHeight(18);
    m_progressBar->setMinimumWidth(250);
    m_progressBar->setMaximumWidth(250);
    m_progressBar->setVisible(false);
    connect(ui->Menu,SIGNAL(menuClick(QString)),this,SLOT(otworzOkno(QString)));

    readSettings();
}

MainWindow::~MainWindow()
{
    writeSettings();
    delete ui;
}

void MainWindow::writeSettings()
{
    QSettings settings(QSettings::IniFormat,
                       QSettings::UserScope,
                       QCoreApplication::organizationName(),
                       QCoreApplication::applicationName());

    settings.setFallbacksEnabled(false);
    settings.beginGroup("mainwindow");

    settings.setValue("geometry",saveGeometry());
    settings.setValue("savestate",saveState() );
    settings.setValue("maximized",isMaximized());
    if (!isMaximized()) {
        settings.setValue("pos",pos());
        settings.setValue("size",size());
    }
    settings.setValue("splitter",ui->splitter->saveState());
    settings.endGroup();
}

void MainWindow::readSettings()
{
    QSettings settings(QSettings::IniFormat,
                       QSettings::UserScope,
                       QCoreApplication::organizationName(),
                       QCoreApplication::applicationName());

    settings.setFallbacksEnabled(false);
    settings.beginGroup("mainwindow");

    restoreGeometry(settings.value("geometry",saveGeometry()).toByteArray());
    restoreState(settings.value("savestate",saveState() ).toByteArray());
    move(settings.value("pos", pos()).toPoint());
    resize(settings.value("size",size() ).toSize());
    if (settings.value("maximized",isMaximized()).toBool())
        showMaximized();
    ui->splitter->restoreState(settings.value("splitter").toByteArray());
    settings.endGroup();
}

bool MainWindow::podlaczDoBazy()
{
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("dziennik");
    db.setUserName("zawody");
    db.setPassword("mypassword");
    db.setPort(3306);
    return db.open();
}

void MainWindow::otworzOkno(QString text)
{
    qDebug() << "Slot wcisnąłeś : " + text;
}
